//
//  InboxViewCtrl.m
//  WeiMo
//
//  Created by he weixian on 13-3-21.
//  Copyright (c) 2013年 . All rights reserved.
//

#import "InboxViewCtrl.h"

#import <QuartzCore/QuartzCore.h>
#import "JSONKit.h"
#import "FMManager.h"
#import "InterfaceDefine.h"
#import "SVPullToRefresh.h"
#import "InboxCell.h"

#import "PersonInboxViewController.h"
#import "LoginViewController.h"
#import "DLog.h"

#define kPageSize (@"20")
#define kInboxKey1 (@"createTimeStr")
#define kInboxKey2 (@"jobsId")
#define kInboxKey3 (@"jobsInformation")

@interface InboxViewCtrl ()
{
    bool mIsUpdate;
    MBProgressHUD *mHUD;
}
@property (nonatomic,retain) NSMutableDictionary *inboxShowDatas;//组装数据
@property (nonatomic,retain) NSMutableArray *inboxMonthIndex;   //月份标记
@property (nonatomic,assign) int pageNo;//页数
@property (nonatomic,assign) BOOL isHaveData;//是否还有数据
@property (nonatomic,retain) NSTimer *inboxTimer;
@end

@implementation InboxViewCtrl
@synthesize inboxShowDatas,inboxMonthIndex;
@synthesize pageNo,isHaveData;
@synthesize inboxTimer;

#pragma mark - system methods

- (void)dealloc
{
    self.inboxShowDatas = nil;
    self.inboxMonthIndex = nil;
    [self.inboxTimer invalidate];
    self.inboxTimer = nil;
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = @"资料收件箱";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[UIBarButtonItem appearance] setTintColor:[UIColor blackColor]];
    
    mIsUpdate = false;
    self.pageNo = 1;
    self.isHaveData = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //[self getInboxData];
    
    [self.tableView addPullToRefreshWithActionHandler:^{
        mIsUpdate = true;
        self.pageNo = 1;
        self.inboxMonthIndex = nil;
        self.inboxShowDatas = nil;
        self.inboxTimer = [NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:@selector(getInboxData) userInfo:nil repeats:NO];
    }];
    
    //下拉事件
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        
        if(self.isHaveData)
        {
            self.pageNo = self.pageNo + 1;
            self.inboxTimer = [NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:@selector(getInboxData) userInfo:nil repeats:NO];
        }
        else
        {
            [self.tableView.infiniteScrollingView stopAnimating];
        }
        
    }];
    self.tableView.backgroundColor =[UIColor colorWithRed:236.0/255 green:237.0/255 blue:241.0/255 alpha:1];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    FMManager *fm = [FMManager sharedInstance];
    if(fm.updateInboxCtrl)
    {
        fm.updateInboxCtrl = FALSE;
        mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        [self.navigationController.view addSubview:mHUD];
        
        // Regiser for HUD callbacks so we can remove it from the window at the right time
        mHUD.delegate = self;
        
        // Show the HUD while the provided method executes in a new thread
        //[mHUD showWhileExecuting:@selector(getData) onTarget:self withObject:nil animated:YES];
        [mHUD show:YES];
        mIsUpdate = true;
        self.pageNo = 1;
        self.inboxMonthIndex = nil;
        self.inboxShowDatas = nil;
        [self getInboxData];
    }
    else
    {
        if(self.inboxMonthIndex == nil || self.inboxMonthIndex.count == 0)
        {
            mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:mHUD];
            
            // Regiser for HUD callbacks so we can remove it from the window at the right time
            mHUD.delegate = self;
            [mHUD show:YES];
            [self getInboxData];
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - get data

- (void)getInboxData
{
    FMManager *fm = [FMManager sharedInstance];
    if(fm.userId)
    {
        DLog(@"fm.userId = %@",fm.userId);
        NSString *urlStr = [NSString stringWithFormat:@"%@/%@",kHttpHost,kGetJobInfo];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlStr]];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setValue:fm.userId forKey:@"userId"];
        [dic setValue:[NSString stringWithFormat:@"%d",self.pageNo] forKey:@"startPage"];
        [dic setValue:kPageSize forKey:@"pageSize"];
        NSString *postStr = [dic JSONString];
        [dic release];
        [request appendPostData:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
        [request setRequestMethod:@"POST"];
        request.delegate = self;
        [request startAsynchronous];
    }
    else
    {
        if(mIsUpdate)
        {
            [self.tableView.pullToRefreshView stopAnimating];
        }

        LoginViewController *loginCtrl = [[LoginViewController alloc] init];
        //loginCtrl.delegate = self;
        [loginCtrl initWithStyle:UITableViewStyleGrouped];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginCtrl];
        [loginCtrl release];
        //nav.navigationBar.barStyle = UIBarStyleBlack;
        UIImage *navImage = [UIImage imageNamed:@"top.png"];
        if ([nav.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
        {
            [nav.navigationBar setBackgroundImage:navImage forBarMetrics:UIBarMetricsDefault];
        }
        else
        {
            UIImageView* imageView = [[[UIImageView alloc] initWithFrame:nav.navigationBar.frame] autorelease];
            imageView.contentMode = UIViewContentModeLeft;
            imageView.image = navImage;
            [nav.navigationBar insertSubview:imageView atIndex:0];
        }
        
        [self.navigationController presentModalViewController:nav animated:YES];
        [nav release];
    }
   
}

#pragma mark - structure array

- (void)structureArray:(NSMutableArray *)array
{
    self.inboxMonthIndex = [[[NSMutableArray alloc] init] autorelease];
    self.inboxShowDatas = [[[NSMutableDictionary alloc] init] autorelease];
    
    for (int i=0; i<array.count; i++)
    {
        NSMutableArray *itemArray = [[NSMutableArray alloc] init];
        NSDictionary *dic1 = [array objectAtIndex:i];
        NSString *dateStr1 = [dic1 objectForKey:kInboxKey1];
        dateStr1 = [self getInboxDate:dateStr1];
        [itemArray addObject:dic1];
        
        for (int j=i+1; j<array.count; j++)
        {
            NSDictionary *dic2 = [array objectAtIndex:j];
            NSString *dateStr2 = [dic2 objectForKey:kInboxKey1];
            dateStr2 = [self getInboxDate:dateStr2];
            
            if ([dateStr2 isEqualToString:dateStr1])
            {
                [itemArray addObject:dic2];
                [array removeObjectAtIndex:j];
                j--;
            }
        }
        
        [self.inboxMonthIndex addObject:dateStr1];
        [self.inboxShowDatas setValue:itemArray forKey:dateStr1];
        [itemArray release];
    }
    
    [self.tableView reloadData];
}

- (void)structureNextArray:(NSMutableArray *)array
{
    //取出新数据中与旧数据最后一个日期相同的数据
    NSString *lastKey = [self.inboxMonthIndex objectAtIndex:(self.inboxMonthIndex.count-1)];
    NSMutableArray *lastArray = [self.inboxShowDatas objectForKey:lastKey];
    for (int i=0; i<array.count; i++)
    {
        NSDictionary *dic = [array objectAtIndex:i];
        NSString *date = [self getInboxDate:[dic objectForKey:kInboxKey1]];
        if ([date isEqualToString:lastKey])
        {
            [lastArray addObject:dic];
            [array removeObjectAtIndex:i];
            i--;
        }
        else    //如果不同直接跳出循环
        {
            //break;
        }
    }
    [self.inboxShowDatas setValue:lastArray forKey:lastKey];
    
    //组装剩下的新数据
    for (int i=0; i<array.count; i++)
    {
        NSMutableArray *itemArray = [[NSMutableArray alloc] init];
        NSDictionary *dic1 = [array objectAtIndex:i];
        NSString *date1 = [self getInboxDate:[dic1 objectForKey:kInboxKey1]];
        [itemArray addObject:dic1];
        for (int j=i+1; j<array.count; j++)
        {
            NSDictionary *dic2 = [array objectAtIndex:j];
            NSString *date2 = [self getInboxDate:[dic2 objectForKey:kInboxKey1]];
            if ([date2 isEqualToString:date1])
            {
                [itemArray addObject:dic2];
                [array removeObjectAtIndex:j];
                j--;
            }
        }
        
        if (self.inboxMonthIndex != nil && self.inboxShowDatas != nil)
        {
            [self.inboxMonthIndex addObject:date1];
            [self.inboxShowDatas setValue:itemArray forKey:date1];
        }
        [itemArray release];
    }
    
    [self.tableView reloadData];
}

#pragma mark - private methods

- (NSString *)getInboxDate:(NSString *)string
{
    //NSLog(@"get ahead:%@",string);
    NSString *dateStr = [string substringFromIndex:5];
    dateStr = [dateStr substringToIndex:2];
    dateStr = [NSString stringWithFormat:@"%@月",dateStr];
    //NSLog(@"get after:%@",dateStr);
    return dateStr;
}

- (void)deleteInboxOneMessage:(NSString *)jobsId
{
    
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.inboxMonthIndex.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *key = [self.inboxMonthIndex objectAtIndex:section];
    NSArray *array  = [self.inboxShowDatas objectForKey:key];
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *inboxCell = @"inboxCell";
    InboxCell *cell = [tableView dequeueReusableCellWithIdentifier:inboxCell];
    if (cell == nil)
    {
        cell = [[[InboxCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:inboxCell] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    NSString *key = [self.inboxMonthIndex objectAtIndex:indexPath.section];
    NSArray *array = [self.inboxShowDatas objectForKey:key];
    NSDictionary *dic = [array objectAtIndex:indexPath.row];
    cell.content.text = [dic objectForKey:kInboxKey3];
    cell.date.text = [dic objectForKey:kInboxKey1];
    //NSLog(@"cell.date:%@",cell.date.text);
    [cell refreshFrame:tableView.frame.size.width];
    
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        NSString *key = [self.inboxMonthIndex objectAtIndex:indexPath.section];
        NSMutableArray *array = [self.inboxShowDatas objectForKey:key];
        NSDictionary *dic = [array objectAtIndex:indexPath.row];
        NSString *jobId = [dic objectForKey:kInboxKey2];
        [self deleteInboxOneMessage:jobId];
        [array removeObjectAtIndex:indexPath.row];
        if (array.count == 0)
        {
            [self.inboxMonthIndex removeObjectAtIndex:indexPath.section];
        }
        else
        {
            [self.inboxShowDatas setValue:array forKey:key];
        }
    }
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 28.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    CGRect rect = CGRectMake(0, 0, tableView.frame.size.width, 24);
    UILabel *lable = [[[UILabel alloc] initWithFrame:rect] autorelease];
    lable.layer.borderColor = [UIColor lightGrayColor].CGColor;
    lable.layer.borderWidth = 1.0;
    lable.textColor = [UIColor blueColor];
    lable.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0];
    lable.text = [NSString stringWithFormat:@"    %@",[self.inboxMonthIndex objectAtIndex:section]];
    return lable;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *key = [self.inboxMonthIndex objectAtIndex:indexPath.section];
    NSMutableArray *array = [self.inboxShowDatas objectForKey:key];
    NSDictionary *dic = [array objectAtIndex:indexPath.row];
    PersonInboxViewController *personCtrl = [[[PersonInboxViewController alloc] init] autorelease];
    personCtrl.title = @"收件列表";
    personCtrl.jobDics = dic;
    personCtrl.delegate = self;
    [self.navigationController pushViewController:personCtrl animated:YES];
}

#pragma mark - ASIHTTPRequestDelegate

- (void)requestFailed:(ASIHTTPRequest *)request
{
    DEnter();
    if(mIsUpdate)
    {
        [self.tableView.pullToRefreshView stopAnimating];
    }
    
    if(mHUD == nil)
    {
        mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        [self.navigationController.view addSubview:mHUD];
        mHUD.delegate = self;
        [mHUD show:YES];
    }
    mHUD.mode =MBProgressHUDModeText;
    mHUD.labelText = @"收件箱为空";
    [mHUD hide:YES afterDelay:1.5];

    
    NSError *error = [request error];
    if (error)
    {
    }
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    DEnter();
    if(mIsUpdate)
    {
        [self.tableView.pullToRefreshView stopAnimating];
    }
    
    NSData *data = [request responseData];
    NSArray *array = [data objectFromJSONData];
    if(array == nil || array.count == 0)
    {
        if(mHUD == nil)
        {
            mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:mHUD];
            mHUD.delegate = self;
            [mHUD show:YES];
        }
        mHUD.mode =MBProgressHUDModeText;
        mHUD.labelText = @"收件箱为空";
        [mHUD hide:YES afterDelay:1.5];
        return;
    }
    
    NSString *item0 = [array objectAtIndex:0];
    if(![item0 isEqualToString:kResponseOk])
    {
        if(mHUD == nil)
        {
            mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:mHUD];
            mHUD.delegate = self;
            [mHUD show:YES];
        }
        mHUD.mode =MBProgressHUDModeText;
        mHUD.labelText = @"收件箱为空";
        [mHUD hide:YES afterDelay:1.5];
        return;
    }
    
    
    if(mHUD)
    {
        mHUD.hidden = YES;
    }
    NSDictionary *datadic = [array objectAtIndex:1];
    NSArray *tempArray = [datadic objectForKey:@"data"];
    if(tempArray.count == 0)
    {
        [self.tableView.infiniteScrollingView stopAnimating];
        self.isHaveData = NO;
        [self.tableView reloadData];
        return;
    }
    else
    {
        self.isHaveData = YES;
    }
    
    //数据是事先按时间降序排好的
    NSMutableArray *resultArray = [[[NSMutableArray alloc] init] autorelease];
    for (int i=0; i<tempArray.count; i++)
    {
        NSDictionary *dic = [tempArray objectAtIndex:i];
        NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
        [item setValue:[dic objectForKey:kInboxKey1] forKey:kInboxKey1];
        [item setValue:[dic objectForKey:kInboxKey2] forKey:kInboxKey2];
        [item setValue:[dic objectForKey:kInboxKey3] forKey:kInboxKey3];
        [resultArray addObject:item];
        [item release];
    }
    
    if (self.pageNo == 1)
    {
        [self structureArray:resultArray];
    }
    else
    {
        [self structureNextArray:resultArray];
    }
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
	// Remove HUD from screen when the HUD was hidded
	[mHUD removeFromSuperview];
	[mHUD release];
	mHUD = nil;
}

#pragma mark -
#pragma mark PersonInboxViewControllerDelegate
-(void) deleteOK
{
    [self getInboxData];
}
@end